package cn.omisheep.au;


import cn.omisheep.au.core.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Map;
import java.util.Set;

/**
 * @author zhou xin chen  😊
 * 联系方式 qq:1269670415  email:xinchenzhou666@gmail.com
 */
//@Component
@Slf4j
@SuppressWarnings("all")
public class AuHelper {

    @Autowired
    private AuKey auKey;
    @Autowired
    private AuFactory auFactory;
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private AuConfig auConfig;
    @Autowired
    private AuValidate auValidate;

    public String getPublicKey() {
        return auKey.getPublicKeyString();
    }

    public String createToken(UserContext user) {
        return jwtHelper.createToken(user);
    }

    public Map<RequestMethod, Map<String, Set<String>>> getAuMap() {
        return auValidate.getAuMap();
    }

    public Map<RequestMethod, Map<String, Set<String>>> getAuExcludeMap() {
        return auValidate.getAuExcludeMap();
    }

    public Map<RequestMethod, Map<String, AuCore.LimitMeta>> getAuLimitMap() {
        return auValidate.getAuLimitMap();
    }


    /**
     * @param auUser      从数据库取出的用户
     * @param requestUser 登录时的用户
     * @return user为null则账号密码错误
     */
    public AuRet login(UserContext auUser, UserContext requestUser) {
        if (auUser != null) {
            // GET
            return new AuRet(auUser);
        }

        if (requestUser == null) {
            return new AuRet();
        }

        UserContext user = (UserContext) auFactory.login(requestUser.getClass(), requestUser.getUsername(), requestUser.getPassword());
        if (user != null) {
            return new AuRet(jwtHelper.createToken(user), user);
        }

        return new AuRet();
    }


    public static class AuRet {
        public String token;
        public UserContext user;

        public boolean loginStatus() {
            return this.user != null;
        }

        public AuRet(String token, UserContext user) {
            this.token = token;
            this.user = user;
        }

        public AuRet(UserContext user) {
            this.user = user;
        }

        public AuRet() {
        }
    }

}
